/**
 * @description: 文件描述
 * @version: 0.0.1
 * @author: ljr
 * @Date: 2023-09-12 15:47:16
 */
import { Provide, Inject, httpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserRoleRecordsModel } from '../entity/user_role_records.method'
import { UserRoleContactModel } from '../entity/user_role_contact.method';

@Provide()
export class UserRoleService {
  @Inject()
  ctx: Context;
  @Inject()
  UserRoleRecordsModel: UserRoleRecordsModel;

  @Inject()
  UserRoleContactModel: UserRoleContactModel;

  /**
   * 创建角色
   * @param {*} roleName 
   * @param {*} roleCode 
   * @returns 
   */
  async createdUserRole(params: any): Promise<any> {
    const { roleName, roleCode } = params;
    const _count = await this.UserRoleRecordsModel.getCountByCode(roleCode);
    if(!_count){
      return await this.UserRoleRecordsModel.createdUserRole(roleName, roleCode);
    }else{
      throw new httpError.BadRequestError("角色编码不可重复");
    }
  }

  /**
   * 获取角色列表
   * @param params 
   * @returns 
   */
  async getUserRoleList(params: any): Promise<any> {
    const { pageNum, pageSize } = params;
    return await this.UserRoleRecordsModel.getUserRoleList(pageNum, pageSize);
  }

  /**
   * 更新角色
   * @param params 
   * @returns 
   */
  async updateUserRole(params: any): Promise<any> {
    const { id, roleName, roleCode } = params;
    return await this.UserRoleRecordsModel.updateUserRole(id, roleName, roleCode);
  }

  /**
   * 删除角色
   * @param id 
   * @returns 
   */
  async delUserRole(id: number): Promise<any> {
    return await this.UserRoleRecordsModel.delUserRole(id);
  }

  /**
   * 更新用户角色信息
   * @param params 
   * @returns 
   */
  async updateUserRoleRecords(params: any): Promise<any> {
    const { userId, roleId } = params;
    //  查询当前用户是否存在角色信息
    const count = await this.UserRoleContactModel.getNum(userId);
    if (count) {
      //  更新用户角色信息
      return await this.UserRoleContactModel.update(userId, roleId);
    } else {
      //  新增用户角色信息
      return await this.UserRoleContactModel.created(userId, roleId);
    }
  }
}